package cn.hlife.com.hlfhaemocyte.maintain.view;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.inuker.bluetooth.library.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

import cn.hlife.com.hlfhaemocyte.MainActivity;
import cn.hlife.com.hlfhaemocyte.R;
import cn.hlife.com.hlfhaemocyte.bluetooth.ClientManager;
import cn.hlife.com.hlfhaemocyte.notify.Transporter;
import cn.hlife.com.hlfhaemocyte.notify.Watcher;
import cn.hlife.com.hlfhaemocyte.utils.LogUtils;
import cn.hlife.com.hlfhaemocyte.utils.SharedPreferencesUtils;
import cn.hlife.com.hlfhaemocyte.utils.TransformDataUtils;
import cn.hlife.com.hlfhaemocyte.view.LoadingDialog;

/**
 * Created by Administrator on 2017/6/24.
 */

public class MaintainFragment extends Fragment{

    private boolean isOpen;
    private ImageView onOff;
    RadioGroup radioGroup;
    int pressed;
    boolean isContinue;
    private DecimalFormat decimalFormat = new DecimalFormat("0.0");
    EditText et_60v, et_15v, et_9v, et_5v;
    private StringBuffer stringBuffer;
    public LoadingDialog meansureDialog;
    long timeMillis;
    public   ImageView  returnImageView;
    public  TextView  middleText,leftText;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.maintain_fragment, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            ((MainActivity)getActivity()).rightText.setVisibility(View.GONE);
            ((MainActivity)getActivity()).middleText.setText("维护");
            ((MainActivity)getActivity()).returnImageView.setVisibility(View.GONE);
        }
    }

    public void initView(View view) {
        view.findViewById(R.id.progress_exhaust).setOnClickListener(onClickListener);
        view.findViewById(R.id.auto_clean).setOnClickListener(onClickListener);
        view.findViewById(R.id.clean_cup).setOnClickListener(onClickListener);
        view.findViewById(R.id.clean_reagent).setOnClickListener(onClickListener);
        view.findViewById(R.id.pour_diluent).setOnClickListener(onClickListener);
        view.findViewById(R.id.pour_lyse).setOnClickListener(onClickListener);
        view.findViewById(R.id.tv_60v).setOnClickListener(onClickListener);
        view.findViewById(R.id.tv_15v).setOnClickListener(onClickListener);
        view.findViewById(R.id.tv_9v).setOnClickListener(onClickListener);
        view.findViewById(R.id.tv_5v).setOnClickListener(onClickListener);
        view.findViewById(R.id.tv_fuzhu).setOnClickListener(onClickListener);
        view.findViewById(R.id.upkeep_button).setOnClickListener(onClickListener);
        view.findViewById(R.id.pour_xxy).setOnClickListener(onClickListener);
        ((MainActivity)getActivity()).middleText.setText("维护");
        ((MainActivity)getActivity()).rightText.setVisibility(View.GONE);
        ((MainActivity)getActivity()).returnImageView.setVisibility(View.GONE);
        et_60v = (EditText) view.findViewById(R.id.et_60v);
        et_15v = (EditText) view.findViewById(R.id.et_15v);
        et_9v = (EditText) view.findViewById(R.id.et_9v);
        et_5v = (EditText) view.findViewById(R.id.et_5v);
        radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
        onOff = (ImageView) view.findViewById(R.id.on_off);
        onOff.setOnClickListener(onClickListener);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
        stringBuffer = new StringBuffer();
        meansureDialog = new LoadingDialog(getContext());
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.radio_button1:
                        String byteStr1 = "aa03020100";
                        byte[] by1 = TransformDataUtils.hexStringToByteArray(byteStr1);
                        connectBluetoothNoDialog(by1);
                        break;
                    case R.id.radio_button2:
                        String byteStr2 = "aa03020200";
                        byte[] by2 = TransformDataUtils.hexStringToByteArray(byteStr2);
                        connectBluetoothNoDialog(by2);
                        break;
                    case R.id.radio_button3:
                        String byteStr3 = "aa03020400";
                        byte[] by3 = TransformDataUtils.hexStringToByteArray(byteStr3);
                        connectBluetoothNoDialog(by3);
                        break;
                    case R.id.radio_button4:
                        String byteStr4 = "aa03020800";
                        byte[] by4 = TransformDataUtils.hexStringToByteArray(byteStr4);
                        connectBluetoothNoDialog(by4);

                        break;
                    case R.id.radio_button5:
                        String byteStr5 = "aa03021000";

                        byte[] by5 = TransformDataUtils.hexStringToByteArray(byteStr5);
                        connectBluetoothNoDialog(by5);
                        break;
                    case R.id.radio_button6:
                        String byteStr6 = "aa03022000";

                        byte[] by6 = TransformDataUtils.hexStringToByteArray(byteStr6);
                        connectBluetoothNoDialog(by6);
                        break;
                    case R.id.radio_button7:
                        String byteStr7 = "aa03024000";

                        byte[] by7 = TransformDataUtils.hexStringToByteArray(byteStr7);
                        connectBluetoothNoDialog(by7);
                        break;
                    case R.id.radio_button8:
                        String byteStr8 = "aa03028000";

                        byte[] by8 = TransformDataUtils.hexStringToByteArray(byteStr8);
                        connectBluetoothNoDialog(by8);
                        break;
                    case R.id.radio_button9:
                        String byteStr9 = "aa03020001";

                        byte[] by9 = TransformDataUtils.hexStringToByteArray(byteStr9);
                        connectBluetoothNoDialog(by9);
                        break;
                    case R.id.radio_button10:
                        String byteStr10 = "aa03020002";

                        byte[] by10 = TransformDataUtils.hexStringToByteArray(byteStr10);
                        connectBluetoothNoDialog(by10);
                        break;
                    case R.id.radio_button11:
                        String byteStr11 = "aa03020004";

                        byte[] by11 = TransformDataUtils.hexStringToByteArray(byteStr11);
                        connectBluetoothNoDialog(by11);
                        break;
                    case R.id.radio_button12:
                        String byteStr12 = "aa03020008";

                        byte[] by12 = TransformDataUtils.hexStringToByteArray(byteStr12);
                        connectBluetoothNoDialog(by12);
                        break;
                    case R.id.radio_button13:
                        String byteStr13 = "aa03020010";

                        byte[] by13 = TransformDataUtils.hexStringToByteArray(byteStr13);
                        connectBluetoothNoDialog(by13);
                        break;
                    case R.id.radio_button14:
                        String byteStr14 = "aa03020020";
                        byte[] by14 = TransformDataUtils.hexStringToByteArray(byteStr14);
                        connectBluetoothNoDialog(by14);
                        break;
                    case R.id.radio_button15:
                        String byteStr15 = "aa03020080";
                        byte[] by15 = TransformDataUtils.hexStringToByteArray(byteStr15);
                        connectBluetoothNoDialog(by15);
                        break;
                }
            }
        });
    }
    public MainActivity.OnBluetoothRecevier onBluetoothRecevier = new MainActivity.OnBluetoothRecevier() {

        boolean isReceive = false;

        @Override
        public void onResultRecever(byte[] value) {
            String tem = TransformDataUtils.toHex(value);
            if (isReceive) {
                stringBuffer.append(tem);
            }
            if (tem.startsWith("bb0306")) {
                onOff.post(new Runnable() {
                    @Override
                    public void run() {
                        if(meansureDialog!=null&&meansureDialog.isShowing()){
                            meansureDialog.dismiss();
                        }
                    }
                });
                ((MainActivity) getActivity()).setOnBluetoothInstance(null);
                byte[] bytes = TransformDataUtils.hexStringToByteArray(tem);
                byte[] bytemp = new byte[2];
                bytemp[0] = bytes[3];
                bytemp[1] = bytes[4];
                final int aa = TransformDataUtils.bytes2short(bytemp);
                radioGroup.post(new Runnable() {
                    @Override
                    public void run() {
                        if (pressed == 60) {
                            double b = 92.4 * aa / 4096;
                            et_60v.setText(decimalFormat.format(b));
                        } else if (pressed == 15) {
                            double b = 36.3 * aa / 4096;
                            et_15v.setText(decimalFormat.format(b));
                        } else if (pressed == 9) {
                            double b = 19.8 * aa / 4096;
                            et_9v.setText(decimalFormat.format(b));
                        } else if (pressed == 5) {
                            double b = 6.6 * aa / 4096;
                            et_5v.setText(decimalFormat.format(b));
                        }
                    }
                });
            } else if (tem.equals("bb03050300")) {//灌注清洁液 结束指令

                //下一步自动清洗
                if (isContinue) {
                    LogUtils.e("-------------->开始自动清洗");
                    byte[] by2 = getBluetoothCommand("etQingXi");
                    if (by2 != null) {
                        connectBluetoothNoDialog(by2);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                }

            } else if (tem.equals("bb03050a00")) {//自动清洗 结束指令
                //下一步程序排堵
                if (isContinue) {
                    LogUtils.e("-------------->开始程序排堵");

                    byte[] by1 = getBluetoothCommand("etPaidu");
                    if (by1 != null) {
                        connectBluetoothNoDialog(by1);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                }

            } else if (tem.equals("bb03050900")) {//程序排堵 结束指令
                //下一步稀释液
                if (isContinue) {
                    LogUtils.e("-------------->开始稀释液");

                    byte[] by = getBluetoothCommand("etXiShiYe");
                    if (by != null) {
                        connectBluetoothNoDialog(by);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                }
            } else if (tem.equals("bb03050500")) {//灌注稀释液 结束指令
                //下一步灌注溶血剂
                if (isContinue) {
                LogUtils.e("-------------->开始溶血剂");
                byte[] by6 = getBluetoothCommand("etQongXueJi");
                if (by6 != null) {
                    connectBluetoothNoDialog(by6);
                } else {
                    Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                }}else{
                    ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                }
            } else if (tem.equals("bb03050200")) {//灌注溶血剂 结束指令
                //下一步 测量 按键

                LogUtils.e("-------------->开始测量");
                if(isContinue){
                    byte[] bytes = TransformDataUtils.hexStringToByteArray("aa03090101");
                    connectBluetoothNoDialog(bytes);
                }else{
                    ((MainActivity) getActivity()).setOnBluetoothInstance(onBluetoothRecevier);

                }


            }
            if (stringBuffer.toString().contains("bb03050100")) {
                isContinue=false;
                long time = (System.currentTimeMillis() - timeMillis )/ 1000;
                LogUtils.e("测量结束-->用时：" + time + "秒");
                LogUtils.e("数据长度：" + stringBuffer.length());
                isReceive = false;
                ((MainActivity) getActivity()).setOnBluetoothInstance(null);
                onOff.post(new Runnable() {
                    @Override
                    public void run() {
                        if (meansureDialog != null && meansureDialog.isShowing()) {
                            meansureDialog.dismiss();
                        }
                    }
                });
            } else if (tem.contains("bb03050101")) {
                LogUtils.e("测量开始-->>>");
                isReceive = true;
                stringBuffer.setLength(0);
                stringBuffer.append(tem);
            }
        }
    };
    public View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int viewID = v.getId();
            switch (viewID) {
                case R.id.on_off:
                    if (isOpen) {
                        isOpen = false;
                        onOff.setImageResource(R.drawable.guan);
                        radioGroup.setVisibility(View.GONE);
                        radioGroup.clearCheck();
                        String byteStr = "aa03020000";
                        byte[] by = TransformDataUtils.hexStringToByteArray(byteStr);
                        connectBluetoothNoDialog(by);

                    } else {
                        isOpen = true;
                        onOff.setImageResource(R.drawable.kai);
                        radioGroup.setVisibility(View.VISIBLE);
                    }
                    break;
                case R.id.progress_exhaust:
                    byte[] by1 = getBluetoothCommand("etPaidu");
                    if (by1 != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                        connectBluetooth(by1);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.auto_clean:
                    byte[] by2 = getBluetoothCommand("etQingXi");
                    if (by2 != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                        connectBluetooth(by2);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.clean_cup:
                    byte[] by3 = getBluetoothCommand("etBeiLiang");
                    if (by3 != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);
                        connectBluetooth(by3);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.clean_reagent:
                    byte[] by4 = getBluetoothCommand("etShiJi");
                    if (by4 != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);
                        connectBluetooth(by4);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.pour_xxy:
                    byte[] by = getBluetoothCommand("etXiShiYe");
                    if (by != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                        connectBluetooth(by);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.pour_diluent:
                    byte[] by5 = getBluetoothCommand("etQingJieYe");
                    if (by5 != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                        connectBluetooth(by5);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.pour_lyse:
                    byte[] by6 = getBluetoothCommand("etQongXueJi");
                    if (by6 != null) {
                        ((MainActivity) getActivity()).setOnBluetoothInstance(null);

                        connectBluetooth(by6);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.tv_60v:
                    String  macAddress2 = readBluetoothMAC("macBluetooth");
                    if(ClientManager.getClient().getConnectStatus(macAddress2)!= Constants.STATUS_DEVICE_CONNECTED){
                        Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
                            break;
                    }
                    byte[] by7 = getBluetoothCommand("et60V");
                    if (by7 != null) {
                        pressed = 60;
                        if(meansureDialog!=null&&!meansureDialog.isShowing()){
                            meansureDialog.show();
                        }
                        ((MainActivity) getActivity()).setOnBluetoothInstance(onBluetoothRecevier);
                        connectBluetoothNoDialog(by7);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.tv_15v:
                    String  macAddress3 = readBluetoothMAC("macBluetooth");
                    if(ClientManager.getClient().getConnectStatus(macAddress3)!= Constants.STATUS_DEVICE_CONNECTED){
                        Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    byte[] by8 = getBluetoothCommand("et15V");
                    if (by8 != null) {
                        if(meansureDialog!=null&&!meansureDialog.isShowing()){
                            meansureDialog.show();
                        }
                        pressed = 15;
                        ((MainActivity) getActivity()).setOnBluetoothInstance(onBluetoothRecevier);

                        connectBluetoothNoDialog(by8);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.tv_9v:
                    String  macAddress4 = readBluetoothMAC("macBluetooth");
                    if(ClientManager.getClient().getConnectStatus(macAddress4)!= Constants.STATUS_DEVICE_CONNECTED){
                        Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    byte[] by9 = getBluetoothCommand("et9V");
                    if (by9 != null) {
                        if(meansureDialog!=null&&!meansureDialog.isShowing()){
                            meansureDialog.show();
                        }
                        pressed = 9;
                        ((MainActivity) getActivity()).setOnBluetoothInstance(onBluetoothRecevier);

                        connectBluetoothNoDialog(by9);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.tv_5v:
                    String  macAddress5 = readBluetoothMAC("macBluetooth");
                    if(ClientManager.getClient().getConnectStatus(macAddress5)!= Constants.STATUS_DEVICE_CONNECTED){
                        Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    byte[] by10 = getBluetoothCommand("et5V");
                    if (by10 != null) {
                        if(meansureDialog!=null&&!meansureDialog.isShowing()){
                            meansureDialog.show();
                        }
                        pressed = 5;
                        ((MainActivity) getActivity()).setOnBluetoothInstance(onBluetoothRecevier);

                        connectBluetoothNoDialog(by10);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.tv_fuzhu:
                    String  macAddress6= readBluetoothMAC("macBluetooth");
                    if(ClientManager.getClient().getConnectStatus(macAddress6)!= Constants.STATUS_DEVICE_CONNECTED){
                        Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    byte[] by11 = getBluetoothCommand("etFuZhu");
                    if (by11 != null) {
                        connectBluetoothNoDialog(by11);
                    } else {
                        Toast.makeText(getContext(), "未填写相应的指令", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.upkeep_button:
                    byte[] by12= getBluetoothCommand("etQingJieYe");
                    if (by12 != null) {
                        isContinue=true;
                        LogUtils.e("-------------->开始清洁液");
                        timeMillis=System.currentTimeMillis();
                        ((MainActivity) getActivity()).setOnBluetoothInstance(onBluetoothRecevier);
                        connectBluetoothNoDialog(by12);
                        onOff.post(new Runnable() {
                            @Override
                            public void run() {
                                if(meansureDialog!=null&&!meansureDialog.isShowing()){
                                    meansureDialog.show();
                                }
                             }
                        });
                    }else {
                        Toast.makeText(getContext(),"未填写相应的指令",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.open_radiotube:
                    break;
            }
        }
    };

    /**
     * 连接蓝牙设备
     */
    public void connectBluetoothNoDialog(byte[] commandByte) {
        String  macAddress2 = readBluetoothMAC("macBluetooth");
        if(ClientManager.getClient().getConnectStatus(macAddress2)== Constants.STATUS_DEVICE_CONNECTED){
            ((MainActivity) getActivity()).writeCommandNoDialog(commandByte);
        }else {
            Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 读取蓝牙的MAC的地址
     */
    public String readBluetoothMAC(String key) {
        String macStr = SharedPreferencesUtils.getInstance().getBluetoothAddress(getContext());
        String macAddress = null;
        try {
            if (!TextUtils.isEmpty(macStr)) {
                JSONObject jsonObject = new JSONObject(macStr);
                macAddress = jsonObject.getString(key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return macAddress;
    }
    /**
     * 连接蓝牙设备
     */
    public void connectBluetooth(byte[] commandByte) {
        String  macAddress2 = readBluetoothMAC("macBluetooth");
        if(ClientManager.getClient().getConnectStatus(macAddress2)== Constants.STATUS_DEVICE_CONNECTED){
            ((MainActivity) getActivity()).writeCommand(commandByte);
        }else {
            Toast.makeText(getContext(),"蓝牙未连接",Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 获取相关功能的蓝牙指令
     */
    public byte[] getBluetoothCommand(String key) {
        String value = SharedPreferencesUtils.getInstance().getMaintainParameter(getActivity());
        byte[] bytes = null;
        if (!TextUtils.isEmpty(value)) {
            try {
                JSONObject jsonObject = new JSONObject(value);
                String jsonValue = jsonObject.getString(key);
                if (!TextUtils.isEmpty(jsonValue)) {
                    bytes = TransformDataUtils.hexStringToByteArray(jsonValue);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }
}
